from flask import abort
from flask import request, render_template, jsonify, session, g, current_app, redirect

from info import constants
from info import db
from info.models import Category, News, User
from info.utils.common import verify_login
from info.utils.image_storage import storage
from info.utils.response_code import RET, error_map
from . import user_blue


# 用户中心
@user_blue.route("/info")
@verify_login
def user_index():
    if not g.user:
        return redirect("/")
    return render_template("news/user.html", data={"user_info": g.user.to_dict()})


# 基本资料
@user_blue.route("/base_info", methods=["GET", "POST"])
@verify_login
def base_info():
    """基本资料"""

    user = g.user

    # 1. 获取传入参数
    # 如果为get请求
    if request.method == "GET":
        return render_template("news/user_base_info.html", data={"user_info": user.to_dict() if g.user else None})

    # POST请求
    nick_name = request.json.get("nick_name")  # 用户名称
    gender = request.json.get("gender")  # 性别
    signature = request.json.get("signature")  # 用户签名

    # 如果为空
    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 如果gender里面没有这些值
    if gender not in (["MAN", "WOMAN"]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 2.更新数据
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    try:
        db.session.commit()
    except Exception as a:
        current_app.logger.error(a)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=error_map.get(RET.DBERR))

    # 3.将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name

    # 4. 返回响应
    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK))


# 上传用户头像
@user_blue.route("/pic_info", methods=["GET", "POST"])
@verify_login
def pic_info():
    """头像上传
    1.判断用户是否登录
    2.是什么请求
    3.上传文件到七牛云
    4.保存数据并返回结果
    """
    user = g.user
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user_info": user.to_dict() if user else None})

    # POST请求上传图片
    avatar = request.files.get("avatar").read()

    try:
        url = storage(avatar)

    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 上传成功会返回一个图片的url地址,如果想访问上传的图片,需要七牛的地址 + 刚刚返回的url
    # http://oyucyko3w.bkt.clouddn.com / + url
    try:
        user.avatar_url = storage(avatar)
        db.session.commit()
    except Exception as b:
        current_app.logger.error(b)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=error_map.get(RET.DBERR))

    # 4.返回上传的结果
    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK), data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


# 用户密码
@user_blue.route("/pass_info", methods=["GET", "POST"])
@verify_login
def pass_info():
    """修改登录密码
    1.判断用户是什么请求
    2.获取新密码,旧密码
    3.查询该用户的旧密码进行校验
    4.返回修改结果
    """

    # 1.判断用户是什么请求
    if request.method == "GET":
        return render_template("news/user_pass_info.html")

    # 2.获取新密码,旧密码
    old_password = request.json.get("old_password")  # 旧密码
    new_password = request.json.get("new_password")  # 新密码

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 3.查询用户的旧密码进行匹配
    user = g.user

    # 如果不能匹配成功
    if not user.check_password(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 匹配成功
    try:
        user.password = new_password
        db.session.commit()

    except Exception as a:
        current_app.logger.error(a)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK))


# 用户收藏新闻
@user_blue.route("/collection")
@verify_login
def collection():
    """用户收藏新闻列表
    1.获取页数
    2.查询数据,用分页函数paginate,分别获取分页数据,当前页,总页数
    3.展示收藏列表
    """

    # 1.获取页数
    page = request.args.get("p", 1)

    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        page = 1

    # 2.查询数据
    user = g.user
    try:
        # 分页查询
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)

        # 获取当前分页数据
        items = paginate.items

        # 获取当前页
        current_page = paginate.page

        # 获取总页数
        total_page = paginate.pages

    except Exception as b:
        current_app.logger.error(b)

    # 3.展示收藏列表
    collection_dict_li = []

    for news in items:
        collection_dict_li.append(news.to_basic_dict())

    data = {
        "collections": collection_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("news/user_collection.html", data=data)


# 编辑新闻
@user_blue.route("/news_release", methods=["POST", "GET"])
@verify_login
def news_release():
    """个人发布新闻
    1.判断是什么请求
    2.查询数据库所有分类数据进行展示
    3.删除分类最新
    """

    # 1.GET请求
    if request.method == "GET":
        categories = []

        # 2.查询分类
        try:
            categories = Category.query.all()

        except Exception as a:
            current_app.logger.error(a)

        category_list = []
        for category in categories:
            category_list.append(category.to_dict())

        # 3.删除最新分类
        category_list.pop(0)
        return render_template("news/user_news_release.html", data={"categories": category_list})

    # POST请求
    # 1.获取提交的数据
    title = request.form.get("title")  # 新闻标题
    category_id = request.form.get("category_id")  # 分类
    digest = request.form.get("digest")  # 摘要
    index_image = request.files.get("index_image")  # 文件上传
    content = request.form.get("content")  # 新闻内容
    print("这是content", content)
    source = "个人发布"

    # 1.1判断数据是否有值
    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 1.2尝试读取图片
    try:
        index_image = index_image.read()
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 2.将标题图片上传到七牛
    try:
        key = storage(index_image)
    except Exception as b:
        current_app.logger.error(b)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 3.初始化新闻模型,并设置相关数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1  # 当前状态1表示正在审核中

    # 4.保存到数据库中
    try:
        db.session.add(news)
        db.session.commit()

    except Exception as c:
        current_app.logger.error(c)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK))


# 新闻列表
@user_blue.route("/news_list")
@verify_login
def news_list():
    user = g.user
    # 获取页数
    page = request.args.get("p", 1)

    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        page = 1

    paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)

    # 获取当前分页数据
    item = paginate.items

    # 获取当前页
    current_page = paginate.page

    # 获取总页数
    total_page = paginate.pages

    news_list = []
    for item in item:
        news_list.append(item.to_review_dict())

    data = {
        "current_page": current_page,
        "total": total_page,
        "news_list": news_list
    }
    return render_template("news/user_news_list.html", data=data)


#  关注接口
@user_blue.route("/follow")
@verify_login
def follow():
    """关注取关"""
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as a:
        current_app.logger.error(a)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1

    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)

        #  获取当前页数据
        follows = paginate.items

        # 获取当前页
        current_page = paginate.page

        # 获取总页数
        total_page = paginate.pages

    except Exception as b:
        current_app.logger.error(b)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page,
    }
    return render_template("news/user_follow.html", data=data)


# 其他用户
@user_blue.route("/other_info")
@verify_login
def other_info():
    """查看其他用户信息"""
    user = g.user

    # 获取其他用户id
    user_id = request.args.get("id")

    if not user_id:
        abort(404)

    # 查询用户模型
    other = None

    try:
        other = User.query.get(user_id)
    except Exception as a:
        current_app.logger.error(a)

    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 组织数据,并返回
    data = {
        "user_info": user.to_dict(),  # 当前用户
        "other_info": other.to_dict(),  # 其他用户(关注的用户)
        "is_followed": is_followed
    }
    return render_template("news/other.html", data=data)


# 其他用户新闻列表
@user_blue.route("/other_news_list")
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 如果参数为空
    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    try:
        user = User.query.get(user_id)
    except Exception as b:
        current_app.logger.error(b)
        return jsonify(errno=RET.DBERR, errmsg=error_map.get(RET.DBERR))

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)

        # 获取当前分页数据
        news_li = paginate.items

        # 获取当前页
        current_page = paginate.page

        # 获取总页数
        total_page = paginate.pages
    except Exception as c:
        current_app.logger.error(c)
        return jsonify(errno=RET.DBERR, errmsg=error_map.get(RET.DBERR))

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK), data=data)